<?php 

lib('io.InputStream');

	class FileInputStream implements InputStream {
		protected $source;
		protected $readed = 0;
		protected $size = 0;
		
		public function __construct(string $file) {
			$this->source = $file;
			$this->size = filesize($this->source);
		}
		
		public function open() {
			$this->source = fopen($this->source, "r");
		}
		
		public function is_opened() {
			return is_resource($this->source);
		}
		public function is_ended() {
			return feof($this->source);
		}
		
		public function close() {
			$this->checks();
			fclose($this->source);
		}
		
		public function read(integer $size = NULL) {
			if ($size == NULL) $size = 1;
			$this->checks();
			$buf = fread($this->source, $size);
			$this->readed += sizeof($buf);
			return $buf; 
		}
		
		public function read_line() {
			$line = '';
			$buf = '';
			try {
				while (true) {
					$buf = $this->read();
					if ($buf == "\n") break;
					$line .= $buf;
				}
			} catch (IOException $e) {
				if (($e->getCode() == IOConst::X_STREAM_ENDED) && $line != '') return $line;
				else throw $e;
			}
			return $line;
		}
		
		public function available() {
			return $this->size - $this->readed;
		}
		
		protected function checks() {
			if (!$this->is_opened()) {
				throw new IOException(IOConst::X_STREAM_NOT_OPENED, "You cannot operate with stream before you open it.");
			}
			if ($this->is_ended()) {
				throw new IOException(IOConst::X_STREAM_ENDED, "Unable to operate with free stream.");
			}
		}
	}

?>